<template>
  <div class="content">
    <el-card class="box-card card-head">
      <el-button type="warning" size="mini" icon="el-icon-back" @click="backEvent">返回</el-button>
      <el-button type="info" size="mini" icon="el-icon-crop" @click="saveEvent('save')" :disabled="globalStatus == 0">保存</el-button>
      <el-button type="success" size="mini" icon="el-icon-postcard" @click="saveEvent('effective')" v-show="globalStatus == 2">生效并保存</el-button>
    </el-card>
    <el-card class="box-card" style="margin:8px 0;">
      <el-form :model="approvalForm" :rules="approvalFormRules" ref="approvalForm" :inline="true" label-position="left" size="small" label-width="80px" :disabled="globalStatus == 0">
        <el-form-item label="审批编号" prop="approvalNumber">
          <el-input v-model="approvalForm.approvalNumber" placeholder="请输入审批编号" style="width:210px;"></el-input>
        </el-form-item>
        <el-form-item label="审批名称" prop="approvalName">
          <el-input v-model="approvalForm.approvalName" placeholder="请输入审批名称" style="width:210px;"></el-input>
        </el-form-item>
        <el-form-item label="业务类型" prop="businessType">
          <el-select v-model="approvalForm.businessType" placeholder="请选择业务类型" style="width:210px;">
            <el-option label="采购需求订单" value="PURCHASE_ORDER"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="条件类型" prop="conditionType">
          <el-select v-model="approvalForm.conditionType" placeholder="请选择条件类型" style="width:210px;">
            <el-option label="金额" value="AMOUNT"></el-option>
            <el-option label="数量" value="QUANTITY"></el-option>
            <el-option label="无条件" value="NONE"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="状态" prop="state" v-show="globalStatus != 2">
          <el-select v-model="approvalForm.state" placeholder="请选择审批状态" style="width:210px;">
            <el-option label="创建" :value="0" disabled></el-option>
            <el-option label="生效" :value="1"></el-option>
            <el-option label="取消" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="操作符" prop="operator">
          <el-select v-model="approvalForm.operator" placeholder="请选择操作符" style="width:210px;">
            <el-option label="大于" value="GT"></el-option>
            <el-option label="大于等于" value="GTE"></el-option>
            <el-option label="小于" value="LT"></el-option>
            <el-option label="小于等于" value="LTE"></el-option>
            <el-option label="等于" value="EQ"></el-option>
            <el-option label="范围" value="RANGE"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最小值" prop="minValue">
          <el-input v-model="approvalForm.minValue" placeholder="请输入最小值" style="width:210px;"></el-input>
        </el-form-item>
        <el-form-item label="最大值" prop="maxValue">
          <el-input v-model="approvalForm.maxValue" :disabled="approvalForm.operator !== 'RANGE'" placeholder="请输入最大值" style="width:210px;"></el-input>
        </el-form-item> -->
        <el-form-item label="备注" label-width="80px">
          <el-input type="textarea" v-model="approvalForm.remark" autosize placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>审批路线</span>
        <div class="header-right" style="float: right;">
          <!-- <el-switch v-model="showProcessOrTable" active-text="流程" inactive-text="表格" style="margin-right:25px;"></el-switch> -->
          <el-button type="text" @click="showFormEvent" :disabled="globalStatus == 0">新增</el-button>
        </div>
      </div>
      <div class="card-process" style="width:100%;overflow: auto;">
        <div class="process-content" style="width:100%;">
          <process-tree v-if="showProcessOrTable" @selectedNode="processTreeSelectedNode" :processTree="processTree"></process-tree>
          <process-table v-if="!showProcessOrTable" :approvalProcessList="approvalProcessList" @tableChange="tableHandlerChange" :globalStatus="globalStatus"></process-table>
        </div>
      </div>
    </el-card>
    <!-- form表单 -->
    <process-form v-if="showForm" :processItem="processItem" :stepNumber="approvalProcessList.length + 1" @formChange="formHandlerChange" :processFormState="processFormState"></process-form>
  </div>
</template>
  
<script>
import ProcessTree from './processTree/ProcessTree.vue'
import ProcessForm from './processForm.vue'
import ProcessTable from './processTable.vue'
import { reqApprovalNumber,reqSavePurchaseInventoryApprove, reqApprovalById, reqUpdateApproval } from "@/api/purchaseInventoryApproveProcess.js";
import { cloneDeep } from 'lodash';
import { Dialog } from "vant";
export default {
  name: 'pruchaseInventoryApproveProcessUpdate',
  components: {
    ProcessTree,
    ProcessForm,
    ProcessTable
  },
  data() {
    return {
      approvalId:"",
      approvalForm:{
        id:"",
        approvalNumber:"",
        approvalName:"",
        businessType:"PURCHASE_ORDER",
        state:0,
        remark:""
      },
      approvalFormRules:{
        approvalNumber:[{required: true,message:'请输入审批编号',trigger:'change'}],
        approvalName:[{required: true,message:'请输入审批名称',trigger:'change'}],
        businessType:[{required: true,message:'请选择业务类型',trigger:'change'}],
        state:[{required: true,message:'请选择审批状态',trigger:'change'}]
      },
      approvalProcessList:[],
      approvalProcessDelList:[],
      showProcessOrTable:false,
      showForm: false,
      processItem:null,
      processFormState:0
    }
  },
  computed:{
    globalStatus(){
      const status = this.$route.query.status;  //0-查看 1-编辑 2-添加
      return status;
    },
    processTree(){
      const list = this.approvalProcessList;
      const tmp = new Array();
      for(let k = 0; k < list.length; k ++){
        const t = list[k];
        const obj = {
          id:t.randomId,
          stepName:t.stepName,
          stepNumber:t.stepNumber,
          approvalList:t.approvalList.map(val => {
            return {
              userId:val.userId,
              username:val.username,
              nickname:val.nickname
            }
          })
        }
        tmp.push(obj);
      }
      return tmp;
    }
  },
  mounted() {
    const approvalId = this.$route.query.approvalId || "";
    this.approvalId = approvalId;
    document.title = '采购入库审批更新'
    //精致环境下进行自动旋转
    const isDevelopment = process.env.NODE_ENV === 'development'
    this.setDomMaxHeight()
    window.addEventListener('resize', this.setDomMaxHeight)
    this.getApprovalNumber();
    this.getApprovalInfoById();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setDomMaxHeight)
  },
  methods: {
    getApprovalNumber(){
      if(this.globalStatus != 2){
        return ;
      }
      reqApprovalNumber().then(response => {
        if(response.data.code === 200){
          const approvalNumber = response.data.data;
          this.approvalForm.approvalNumber = approvalNumber;
        }
        console.log('获取审批编号api',response);
      }, error => {
        console.log("获取审批编号api",error);
      })
    },
    setDomMaxHeight() {
      const dom = document.querySelector('.card-process')
      const h = window.innerHeight - dom.offsetTop - 20;
      console.log(h)
      this.$nextTick(() => {
        dom.style.height = h + 'px'
      })
    },
    showFormEvent() {
      this.processItem = null;
      this.processFormState = 0;
      this.showForm = true
    },
    formHandlerChange(value) {
      this.showForm = false;
      console.log("form数据===>",value);
      if(value !== null){
        const index = this.approvalProcessList.findIndex(val => val.randomId === value.randomId);
        console.log(index);
        if(index === -1){
          this.approvalProcessList.push(value);
        } else {
          this.approvalProcessList.splice(index,1,value);
        }
      }
      this.$forceUpdate();
      console.log('approvalProcessList',this.approvalProcessList);
    },
    tableHandlerChange(params,type){
      const { stepNumber,stepName,approvalList,remark,randomId } = params;
      console.log("randomId",randomId);
      const approvalProcessList = this.approvalProcessList;
      if(type === 'edit'){
        const approvalProcess = approvalProcessList.find(val => val.randomId === randomId);
        this.processItem = approvalProcess;
        this.processFormState = 1;
        this.showForm = true;
      } else if(type === 'delete'){
        const index = approvalProcessList.findIndex(val => val.randomId === randomId);
        if(index !== approvalProcessList.length - 1){
          for(let i = index; i < approvalProcessList.length; i ++){
            approvalProcessList[i].stepNumber = approvalProcessList[i].stepNumber - 1;
          }
        }
        this.approvalProcessDelList.push(approvalProcessList[index]);
        approvalProcessList.splice(index,1);
      }
    },
    processTreeSelectedNode(node){
      console.log("选中的节点:",node);
    },
    backEvent() {
      this.$router.push('/purchaseInventoryApproveProcess')
    },
    saveEvent(type){
      let isValidate = false;
      this.$refs.approvalForm.validate(validate => {
        isValidate = validate;
      })
      if(!isValidate){
        return ;
      }
      const approvalProcessList = cloneDeep(this.approvalProcessList);
      if(approvalProcessList.length === 0){
        Dialog.alert({title:'提示',message:'未填写审批步骤，请填写至少一条审批步骤后再保存'}).then(confirm => {});
        return;
      }
      const { id,approvalNumber,approvalName,businessType,conditionType,state,operator,minValue,maxValue,remark } = this.approvalForm;
      const parameter = {
        id:id,
        configName:approvalName,
        configCode:approvalNumber,
        businessType:businessType,
        state:type === 'effective' ? 1 : state,
        klApprovalStepList:[],
        remark:remark
      }
      for(let k = 0; k < approvalProcessList.length; k++){
        const t = approvalProcessList[k];
        const klApprovalStep = {
          ...t,
          klApprovalUserList:t.approvalList
        }
        parameter.klApprovalStepList.push(klApprovalStep);
      }
      if(this.globalStatus == 1 && this.approvalProcessDelList.length > 0){
        this.approvalProcessDelList.forEach(v => v.deleted = true);
        parameter.klApprovalStepList = [...parameter.klApprovalStepList,...this.approvalProcessDelList];
      }
      let executeMethod = null;
      if(this.globalStatus == 1){
        executeMethod = reqUpdateApproval;
      } else if(this.globalStatus == 2){
        executeMethod = reqSavePurchaseInventoryApprove;
      }
      console.log("请求参数===>",parameter);
      executeMethod(parameter).then(response => {
        if(response.data.code === 200){
          Dialog.alert({title:'提示',message:'保存成功'}).then(confirm => {
            this.backEvent();
          });
        }
        console.log("保存审批信息api",response);
      }, error => {
        Dialog.alert({title:'提示',message:'保存失败，请稍后重试'}).then(confirm => {});
        console.log("保存审批信息api",error);
      })
    },
    getApprovalInfoById(){
      const id = this.approvalId;
      if(!id || this.globalStatus == 2){
        return;
      }
      reqApprovalById(id).then(response => {
        if(response.data.code === 200){
          const { id,configCode,configName,businessType,conditionType,maxValue,minValue,operator,state,klApprovalStepList } = response.data.data;
          this.approvalForm.id = id || "";
          this.approvalForm.approvalNumber = configCode || "";
          this.approvalForm.approvalName = configName || "";
          this.approvalForm.businessType = businessType || "";
          this.approvalForm.state = state;
          this.approvalProcessList = klApprovalStepList.map(val => {
            return {
              ...val,
              randomId:val.id,
              approvalList:val.klApprovalUserList
            }
          });
        }
        console.log("获取审批信息通过id",response);
      }, error => {
        console.log("获取审批信息通过id",error);
      })
    }
  }
}
</script>
  
<style lang='scss' scoped>
.content {
  width: 100%;
  height: 100%;
  padding: 10px;
}
@media screen and (min-width:300px) and (max-width:600px) {
    .el-message-box{
        width:320px;
    }
    .card-head{
      padding-top:60px;
    }
}
.card-process{
    width:100%;
    overflow:visible;

    .process-content{
      width: 100%;
      height: auto;
      position: relative;
      z-index:0;
      transform-origin: 50% 0px 0px;
      display: flex;
    }
}
/*
::v-deep .el-table__header th {
  padding: 0;
}
::v-deep .el-table__row {
  margin-bottom: 15px;
}
::v-deep .el-table .el-table__cell{
  padding: 0;
}
*/
</style>